<?php

namespace App\Http\Controllers\Api\Admin;

use App\ActiveParty;
use App\Activity;
use App\ActivityGroupRefund;
use App\ActivityJoin;
use App\ActivityRefund;
use App\Http\Controllers\Api\PaymentController;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\InvoiceLookUp;
use App\InvoiceRecord;
use App\Orders;
use App\Units;
use App\User;
use App\UserActivity;
use App\UserXUnit;
use Endroid\QrCode\QrCode;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Intervention\Image\Facades\Image;

class ActivityController extends Controller
{
    /**
     * 活动方列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivePartyList(Request $request){
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $keyword = !is_null($request->get('keyword')) ? $request->get('keyword') : '';

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        /** @var ActiveParty $activeParty */
        $activePartyList = ActiveParty::whereNull('deleted_at');

        if($keyword != ''){
            $activePartyList->where('name','like','%'.trim($keyword).'%');
        }

        $pageInfo['total'] = $activePartyList->count();

        $activePartyList = $activePartyList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($activePartyList) > 0){
            foreach($activePartyList as $activeParty){
                $activeParty->logo_url = FileManager::getImgUrl($activeParty->logo_id);

                if($activeParty->type == 1){
                    $activeParty->type_name = '官方';
                }else{
                    $activeParty->type_name = '非官方';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activePartyList,'page_info' => $pageInfo]);
    }

    /**
     * 活动房详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivePartyDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $activeParty = ActiveParty::whereId($id)->first();
        if($activeParty){
            $activeParty->logo_url = FileManager::getImgUrl($activeParty->logo_id);

            if($activeParty->type == 1){
                $activeParty->type_name = '官方';
            }else{
                $activeParty->type_name = '非官方';
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activeParty]);
    }

    /**
     * 设置活动方
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setActiveParty(Request $request){
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;
        $logoId  = !is_null($request->get('logo_id')) ? $request->get('logo_id') : 0;
        $name    = !is_null($request->get('name')) ? $request->get('name') : '';
        $type    = !is_null($request->get('type')) ? $request->get('type') : 0;

        $activeParty = ActiveParty::whereId($id)->first();
        if(!$activeParty)
            $activeParty = new ActiveParty();

        $activeParty->logo_id          = $logoId;
        $activeParty->name             = $name;
        $activeParty->type             = $type;
        $activeParty->status           = 1;
        $activeParty->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $activeParty]);
    }

    /**
     * 删除活动房
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delActiveParty(Request $request){
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;

        $activeParty = ActiveParty::whereId($id)->first();
        if(!$activeParty)
            return response()->json(['level' => 'error','message' => '活动方不存在']);

        $activeParty->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $activeParty]);
    }

    /**
     * 获取活动列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivityList(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $limit          = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page           = !is_null($request->get('page')) ? $request->get('page') : 1;
        $keyword        = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $activePartyId  = !is_null($request->get('active_party_id')) ? $request->get('active_party_id') : 0;
        $status         = !is_null($request->get('status')) ? $request->get('status') : 0;
        $isOfficial     = !is_null($request->get('is_official')) ? $request->get('is_official') : '';

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
            'keyword' => $keyword,
            'active_party_id' => $activePartyId,
            'status' => $status,
            'is_official' => $isOfficial
        ];

        $page = $page - 1;

        $unitId = 0;
        if($adminUser->role == 0){
            $unitAuth = CommonManager::isUnitAuth($adminUser->id);
            if($unitAuth){
                $userXUnit = UserXUnit::whereUserId($adminUser->id)->first();
                if($userXUnit){
                    $unitId = $userXUnit->unit_id;
                }
            }
        }

        $activityIds = [];
        $allUnitXUserList = UserXUnit::whereUnitId($unitId)->get();
        if(count($allUnitXUserList) > 0){
            foreach($allUnitXUserList as $allUnitXUser){
                $unitAuth = CommonManager::isUnitAuth($allUnitXUser->user_id);
                if($unitAuth){
                    $activityJoinList = ActivityJoin::whereUserId($allUnitXUser->user_id)->whereStatus(1)->get();
                    if(count($activityJoinList) > 0){
                        foreach($activityJoinList as $activityJoin){
                            array_push($activityIds,$activityJoin->activity_id);
                        }
                    }
                }
            }
        }

        array_unique($activityIds);

        $activityList = CommonManager::getActivityList('list',$limit,$page,$keyword,$isOfficial,$activePartyId,$status,0,null,$activityIds,$unitId);
        $pageInfo['total'] = CommonManager::getActivityNum($keyword,$activePartyId,$status,0);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityList,'page_info' => $pageInfo]);
    }

    /**
     * 获取活动详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivityDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $activity = CommonManager::getActivityList('detail',0,0,'','',0,0,0,null,$id);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activity]);
    }

    /**
     * 活动报名表字段
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSignUpTableField(Request $request){
        $data = [
            (object)[
                'name'  => '姓名',
                'value' => 'realname',
            ],
            (object)[
                'name'  => '手机',
                'value' => 'phone',
            ],
            (object)[
                'name'  => '公司',
                'value' => 'company',
            ],
            (object)[
                'name'  => '岗位',
                'value' => 'position',
            ],
            (object)[
                'name'  => '邮箱',
                'value' => 'email',
            ],
            (object)[
                'name'  => '备注',
                'value' => 'remark',
            ]
        ];

        return response()->json(['level' => 'success','message' => '获取成功','data' => $data]);
    }

    /**
     * 设置活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setActivity(Request $request){
        $id                 =  !is_null($request->get('id'))?$request->get('id') : 0;
        $name               =  !is_null($request->get('name'))?$request->get('name') : '';
        $activePartyId      =  !is_null($request->get('active_party_id')) ? $request->get('active_party_id') : 0;
        $imgId              =  !is_null($request->get('img_id')) ? $request->get('img_id') : 0;
        $desc               =  $request->get('desc');
        $province           =  $request->get('province');
        $city               =  $request->get('city');
        $area               =  $request->get('area');
        $address            =  $request->get('address');
        $startTime          =  $request->get('start_time');
        $endTime            =  $request->get('end_time');
        $cost               =  !is_null($request->get('cost')) ? $request->get('cost') : 0.00;
        $sort               =  !is_null($request->get('sort'))?$request->get('sort'):0;
        $detail             =  !is_null($request->get('detail')) ? $request->get('detail') : '';
        $signUpTable        =  $request->get('sign_up_table');
        $isReview           =  !is_null($request->get('is_review')) ? $request->get('is_review') : 0;

        if($activePartyId == '' || $activePartyId == 0)
            return response()->json(['level' => 'error','message' => '请选择活动方']);

        if(!is_array($signUpTable) || (is_array($signUpTable) && count($signUpTable) <= 0))
            return response()->json(['level' => 'error','message' => '请勾选报名表字段']);

        $activeParty = ActiveParty::whereId($activePartyId)->first();
        if(!$activeParty)
            return response()->json(['level' => 'error','message' => '活动方不存在']);

        /** @var Activity $projectInfo */
        $newActivity = Activity::whereId($id)->first();
        if(!$newActivity)
            $newActivity = new Activity();

        if(!is_null($name))$newActivity->name                    = $name;
        $newActivity->img_id                                     = $imgId;
        if(!is_null($desc))$newActivity->desc                    = $desc;
        if(!is_null($province))$newActivity->province            = $province;
        if(!is_null($city))$newActivity->city                    = $city;
        if(!is_null($area))$newActivity->area                    = $area;
        if(!is_null($address))$newActivity->address              = $address;
        if(!is_null($startTime))$newActivity->start_time         = $startTime;
        if(!is_null($endTime))$newActivity->end_time             = $endTime;
        if(!is_null($detail))$newActivity->detail                = $detail;
        $newActivity->cost                                       = $cost;
        $newActivity->sort                                       = $sort;
        $newActivity->status                                     = 1;
        $newActivity->active_party_id                            = $activePartyId;
        $newActivity->sign_up_table                              = json_encode($signUpTable);
        $newActivity->is_review                                  = $isReview;
        $newActivity->save();

        if($newActivity->sign_qr_code_img_id == '' || is_null($newActivity->sign_qr_code_img_id)){
            $scene = "activityId=".$newActivity->id;
            $path  = '/pages/details/activityDetail/activityDetail?' . $scene . '&type=check';

            $signQrCodeImgContent = WechatLogin::getWxaCodeBYToken($path);

            if($signQrCodeImgContent){
                $filoInfo = FileManager::saveFileByFileContent($signQrCodeImgContent,"qr_code_" . $newActivity->id . ".jpg",'',"oss");
                $newImage = new Images();
                $newImage->file_id          = $filoInfo->id;
                $newImage->img_name         = "qr_code_" . $newActivity->id . ".jpg";
                $newImage->img_type         = $filoInfo->file_type;
                $newImage->save();

                $newActivity->sign_qr_code_img_id = $newImage->id;
                $newActivity->save();

            }else{
                return response()->json(['level' => 'error','message' => '二维码生成失败,请联系客服']);
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newActivity]);
    }

    /**
     * 删除活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delActivity(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $activity = Activity::whereId($id)->first();
        if(!$activity)
            return response()->json(['level' => 'error','message' => '删除失败']);

        $userActivityList = ActivityJoin::whereActivityId($activity->id)->get();
        if(count($userActivityList) > 0){
            foreach($userActivityList as $userActivity){
                $userActivity->delete();
            }
        }

        $activity->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);

    }

    /**
     * 获取活动报名人数接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivitySignInList(Request $request){
        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;
        $page      = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit     = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $isSign    = !is_null($request->get('is_sign')) ? $request->get('is_sign') : 'default';

        $pageInfo = [
            'page' => $page,
            'limit' => $limit,
        ];

        /** @var ActivityJoin $activityJoin */
        $activityJoinList = ActivityJoin::whereActivityId($activityId);

        if($isSign != 'default' && $isSign !== ''){
            $activityJoinList->whereIsSign($isSign);
        }

        $activityJoinList = $activityJoinList->where('status' , '<>' , 0);

        $pageInfo['total'] = $activityJoinList->count();

        $activityJoinList = $activityJoinList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($activityJoinList) > 0){
            foreach($activityJoinList as $activityJoin){
                $userInfo = CommonManager::getUserBasicInfo($activityJoin->user_id);
                $activityJoin->nickname     = $userInfo ? $userInfo['nickname'] : '';
                $activityJoin->realname     = $userInfo ? $userInfo['realname'] : '';
                $activityJoin->phone        = $userInfo ? $userInfo['phone'] : '';
                $activityJoin->photo_url    = $userInfo ? $userInfo['photo_url'] : '';
                $activityJoin->cost = '';

                $info_list = [];
                $activity = Activity::whereId($activityJoin->activity_id)->first();
                if($activity){
                    $activityJoin->cost = $activity->cost;

                    $signUpTAble = json_decode($activity->sign_up_table);

                    if(is_array($signUpTAble) && in_array('realname',$signUpTAble)){
                        array_push($info_list,$activityJoin->realname);
                    }

                    if(is_array($signUpTAble) && in_array('phone',$signUpTAble)) {
                        array_push($info_list,$activityJoin->phone);
                    }

                    if(is_array($signUpTAble) && in_array('company',$signUpTAble)){
                        array_push($info_list,$activityJoin->company);
                    }

                    if(is_array($signUpTAble) && in_array('position',$signUpTAble)){
                        array_push($info_list,$activityJoin->position);
                    }

                    if(is_array($signUpTAble) && in_array('email',$signUpTAble)){
                        array_push($info_list,$activityJoin->email);
                    }

                    if(is_array($signUpTAble) && in_array('remark',$signUpTAble)){
                        array_push($info_list,$activityJoin->remark);
                    }

                }

                $activityJoin->sign_up_info_list = $info_list;

                if($activityJoin->is_sign == 1){
                    $activityJoin->sign_status = '已签到';
                }else{
                    $activityJoin->sign_status = '未签到';
                }

                if($activityJoin->status == 1){
                    $activityJoin->status_name = '已报名';
                }elseif($activityJoin->status == 2){
                    $activityJoin->status_name = '未审核';
                }elseif($activityJoin->status == 3){
                    $activityJoin->status_name = '审核失败';
                }
            }
        }

        $signUpTAbleArr = [];

        $thisActivity = Activity::whereId($activityId)->first();
        if($thisActivity){
            $signUpTAble = json_decode($thisActivity->sign_up_table);

            if(is_array($signUpTAble) && in_array('realname',$signUpTAble)){
                $realname = (object)[
                    'name'  => '姓名',
                    'value' => 'realname',
                ];
                array_push($signUpTAbleArr,$realname);
            }

            if(is_array($signUpTAble) && in_array('phone',$signUpTAble)) {
                $phone = (object)[
                    'name'  => '手机',
                    'value' => 'phone',
                ];
                array_push($signUpTAbleArr,$phone);

            }

            if(is_array($signUpTAble) && in_array('company',$signUpTAble)){
                $company = (object)[
                    'name'  => '公司',
                    'value' => 'company',
                ];
                array_push($signUpTAbleArr,$company);

            }

            if(is_array($signUpTAble) && in_array('position',$signUpTAble)){
                $position = (object)[
                    'name'  => '岗位',
                    'value' => 'position',
                ];
                array_push($signUpTAbleArr,$position);
            }

            if(is_array($signUpTAble) && in_array('email',$signUpTAble)){
                $email = (object)[
                    'name'  => '邮箱',
                    'value' => 'email',
                ];
                array_push($signUpTAbleArr,$email);
            }

            if(is_array($signUpTAble) && in_array('remark',$signUpTAble)){
                $remark = (object)[
                    'name'  => '备注',
                    'value' => 'remark',
                ];
                array_push($signUpTAbleArr,$remark);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityJoinList,'page_info' => $pageInfo,'sign_up_table' => $signUpTAbleArr]);
    }

    public function getSignUpSuccess(Request $request){
        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;

        /** @var ActivityJoin $activityJoin */
        $activityJoinList = ActivityJoin::whereActivityId($activityId)->whereStatus(1)->orderBy('created_at','desc')->get();;
        if(count($activityJoinList) > 0){
            foreach($activityJoinList as $activityJoin){
                $userInfo = CommonManager::getUserBasicInfo($activityJoin->user_id);
                $activityJoin->nickname     = $userInfo ? $userInfo['nickname'] : '';
                $activityJoin->realname     = $userInfo ? $userInfo['realname'] : '';
                $activityJoin->phone        = $userInfo ? $userInfo['phone'] : '';
                $activityJoin->photo_url    = $userInfo ? $userInfo['photo_url'] : '';
                $activityJoin->cost = '';

                $info_list = [];
                $activity = Activity::whereId($activityJoin->activity_id)->first();
                if($activity){
                    $activityJoin->cost = $activity->cost;

                    $signUpTAble = json_decode($activity->sign_up_table);

                    if(is_array($signUpTAble) && in_array('realname',$signUpTAble)){
                        array_push($info_list,$activityJoin->realname);
                    }

                    if(is_array($signUpTAble) && in_array('phone',$signUpTAble)) {
                        array_push($info_list,$activityJoin->phone);
                    }

                    if(is_array($signUpTAble) && in_array('company',$signUpTAble)){
                        array_push($info_list,$activityJoin->company);
                    }

                    if(is_array($signUpTAble) && in_array('position',$signUpTAble)){
                        array_push($info_list,$activityJoin->position);
                    }

                    if(is_array($signUpTAble) && in_array('email',$signUpTAble)){
                        array_push($info_list,$activityJoin->email);
                    }

                    if(is_array($signUpTAble) && in_array('remark',$signUpTAble)){
                        array_push($info_list,$activityJoin->remark);
                    }

                }

                $activityJoin->sign_up_info_list = $info_list;

                if($activityJoin->is_sign == 1){
                    $activityJoin->sign_status = '已签到';
                }else{
                    $activityJoin->sign_status = '未签到';
                }

                if($activityJoin->status == 1){
                    $activityJoin->status_name = '已报名';
                }elseif($activityJoin->status == 2){
                    $activityJoin->status_name = '未审核';
                }elseif($activityJoin->status == 3){
                    $activityJoin->status_name = '审核失败';
                }
            }
        }

        $signUpTAbleArr = [];

        $thisActivity = Activity::whereId($activityId)->first();
        if($thisActivity){
            $signUpTAble = json_decode($thisActivity->sign_up_table);

            if(is_array($signUpTAble) && in_array('realname',$signUpTAble)){
                $realname = (object)[
                    'name'  => '姓名',
                    'value' => 'realname',
                ];
                array_push($signUpTAbleArr,$realname);
            }

            if(is_array($signUpTAble) && in_array('phone',$signUpTAble)) {
                $phone = (object)[
                    'name'  => '手机',
                    'value' => 'phone',
                ];
                array_push($signUpTAbleArr,$phone);

            }

            if(is_array($signUpTAble) && in_array('company',$signUpTAble)){
                $company = (object)[
                    'name'  => '公司',
                    'value' => 'company',
                ];
                array_push($signUpTAbleArr,$company);

            }

            if(is_array($signUpTAble) && in_array('position',$signUpTAble)){
                $position = (object)[
                    'name'  => '岗位',
                    'value' => 'position',
                ];
                array_push($signUpTAbleArr,$position);
            }

            if(is_array($signUpTAble) && in_array('email',$signUpTAble)){
                $email = (object)[
                    'name'  => '邮箱',
                    'value' => 'email',
                ];
                array_push($signUpTAbleArr,$email);
            }

            if(is_array($signUpTAble) && in_array('remark',$signUpTAble)){
                $remark = (object)[
                    'name'  => '备注',
                    'value' => 'remark',
                ];
                array_push($signUpTAbleArr,$remark);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityJoinList,'sign_up_table' => $signUpTAbleArr]);
    }

    /**
     * 报名审核接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activitySignUpReview(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        $type = !is_null($request->get('type')) ? $request->get('type') : 'pass';

        $activityJoin = ActivityJoin::whereId($id)->first();
        if(!$activityJoin)
            return response()->json(['level' => 'error','message' => '报名信息不存在']);

        $activity = Activity::whereId($activityJoin->activity_id)->first();
        if(!$activity)
            return response()->json(['level' => 'error','message' => '活动不存在']);

        if($activity->is_review != 1)
            return response()->json(['level' => 'error','message' => '该活动不需要审核']);

        $thisOrder = Orders::whereOrderNum($activityJoin->order_num)->first();
        if(!$thisOrder)
            return response()->json(['level' => 'error','messsage' => '活动订单不存在']);

        if($activityJoin->status == 1)
            return response()->json(['level' => 'error','message' => '审核已通过']);

        if($activityJoin->status == 3)
            return response()->json(['level' => 'error','message' => '审核已拒绝']);

        if($activityJoin->status == 0)
            return response()->json(['level' => 'error','message' => '审核异常']);

        if($type == 'pass'){
            $activityJoin->status = 1;
            $activityJoin->save();
        }elseif($type == 'refuse'){
            $activityJoin->status = 3;
            $activityJoin->save();

            $refundResult = PaymentController::Refund($thisOrder,'报名审核拒绝');
            if($refundResult && $refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS'){
                $newActivityGroupRefund = new ActivityRefund();
                $newActivityGroupRefund->user_id                           = $thisOrder->user_id;
                $newActivityGroupRefund->order_num                         = $thisOrder->order_num;
                $newActivityGroupRefund->reason                            = '报名审核拒绝';
                $newActivityGroupRefund->save();
            }else{
                $newActivityGroupRefund = new ActivityRefund();
                $newActivityGroupRefund->user_id                           = $thisOrder->user_id;
                $newActivityGroupRefund->order_num                         = $thisOrder->order_num;
                $newActivityGroupRefund->reason                            = '报名审核拒绝';
                $newActivityGroupRefund->status                            = 2;
                $newActivityGroupRefund->failure_reason                    = isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '申请退款失败';
                $newActivityGroupRefund->save();

                $thisOrder->is_refund = 2;
                $thisOrder->save();
            }
        }else{
            return response()->json(['level' => 'error','message' => '系统错误']);
        }

        return response()->json(['level' => 'success','message' => '操作成功']);
    }

    /**
     * 查询退款结果（加入定时任务）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function lookOverRefundResult(Request $request){
        /** @var ActivityRefund $newActivityGroupRefund */
        $newActivityGroupRefundList = ActivityRefund::whereStatus(0)->orderBy('created_at','desc')->get();
        if(count($newActivityGroupRefundList) > 0){
            foreach($newActivityGroupRefundList as $newActivityGroupRefund){
                $thisOrder = Orders::whereOrderNum($newActivityGroupRefund->order_num)->whereIsRefund(0)->first();
                if($thisOrder){
                    $refundResult = PaymentController::selectRefund($thisOrder);
                    if(!empty($refundResult) && $refundResult['return_code'] == 'SUCCESS' && $refundResult['result_code'] == 'SUCCESS'){
                        if($refundResult['refund_status_0'] == 'SUCCESS'){
                            $newActivityGroupRefund->status      = 1;
                            $newActivityGroupRefund->refund_time = isset($refundResult['refund_success_time_0']) ? $refundResult['refund_success_time_0'] : date('Y-m-d H:i:s',time());
                            $newActivityGroupRefund->save();

                            $thisOrder->is_refund = 1;
                            $thisOrder->save();
                        }elseif($refundResult['refund_status_0'] == 'REFUNDCLOSE'){
                            $newActivityGroupRefund->status      = 2;
                            $newActivityGroupRefund->failure_reason = '退款关闭';
                            $newActivityGroupRefund->save();

                            $thisOrder->is_refund = 2;
                            $thisOrder->save();
                        }elseif($refundResult['refund_status_0'] == 'CHANGE'){
                            $newActivityGroupRefund->status      = 2;
                            $newActivityGroupRefund->failure_reason = '退款异常,可前往商户平台（pay.weixin.qq.com）-交易中心，手动处理此笔退款。';
                            $newActivityGroupRefund->save();

                            $thisOrder->is_refund = 2;
                            $thisOrder->save();
                        }
                    }else{
                        $newActivityGroupRefund->status         = 2;
                        $newActivityGroupRefund->failure_reason = isset($refundResult['err_code_des']) ? $refundResult['err_code_des'] : '微信退款申请接收失败';
                        $newActivityGroupRefund->save();
                    }
                }
            }
        }

    }

    /**
     * 活动确认签到
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activitySign(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $activityJoin = ActivityJoin::whereId($id)->whereStatus(1)->first();
        if(!$activityJoin)
            return response()->json(['level' => 'error','message' => '报名信息不存在']);

        if($activityJoin->is_sign == 1)
            return response()->json(['level' => 'error','message' => '已签到，请勿重复操作']);

        $activityJoin->is_sign = 1;
        $activityJoin->save();

        return response()->json(['level' => 'success','message' => '签到成功','data' => $activityJoin]);
    }

    /**
     * 申请开票
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function submitOpenInvoiceApply(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;

        if((integer)$adminUser->role !== 0)
            return response()->json(['level' => 'error','message' => '无法操作']);

        $isUnitAuth = CommonManager::isUnitAuth($adminUser->id);
        if(!$isUnitAuth)
            return response()->json(['level' => 'error','message' => '请先完成单位认证']);

        $unitXUser = UserXUnit::whereUserId($adminUser->id)->whereIsAdmin(1)->first();
        if(!$unitXUser)
            return response()->json(['level' => 'error','message' => '无权限操作']);

        $unit = Units::whereId($unitXUser->unit_id)->first();
        if(!$unit)
            return response()->json(['level' => 'error','message' => '单位不存在']);

        if(!in_array($unit->is_member_unit,[1,2]))
            return response()->json(['level' => 'error','message' => '请先完成入驻申请']);

        $activity = Activity::whereId($activityId)->first();
        if(!$activity)
            return response()->json(['level' => 'error','message' => '活动不存在']);

        $invoiceLookUp = InvoiceLookUp::whereUnitId($unit->id)->whereIsDefault(1)->first();
        if(!$invoiceLookUp)
            return response()->json(['level' => 'error','message' => '请先设置发票抬头']);

        $invoiceRecord = InvoiceRecord::whereActivityId($activity->id)->whereUnitId($unit->id)->first();
        if($invoiceRecord)
            return response()->json(['level' => 'error','message' => '已经提交过了，请勿重复提交']);

        $activityJoinNum = 0;
        $activityJoinList = ActivityJoin::whereActivityId($activity->id)->whereStatus(1)->get();
        if(count($activityJoinList) > 0){
            foreach($activityJoinList as $activityJoin){
                $userUnitAuth = CommonManager::isUnitAuth($activityJoin->user_id);
                if($userUnitAuth){
                    $activityJoinNum += 1;
                }
            }
        }

        if($activityJoinNum <= 0 || $activity->cost <= 0)
            return response()->json(['level' => 'error','message' => '申请失败']);

        $invoiceRecord = new InvoiceRecord();
        $invoiceRecord->activity_id              = $activity->id;
        $invoiceRecord->unit_id                  = $unit->id;
        $invoiceRecord->unit_name                = $unit->name;
        $invoiceRecord->unit_province            = $unit->province;
        $invoiceRecord->unit_city                = $unit->city;
        $invoiceRecord->unit_area                = $unit->area;
        $invoiceRecord->unit_address             = $unit->address;
        $invoiceRecord->unit_phone               = $unit->contact_number;
        $invoiceRecord->email_address            = $invoiceLookUp->email_address;
        $invoiceRecord->Invoice_tax_number       = $invoiceLookUp->Invoice_tax_number;
        $invoiceRecord->bank_account             = $invoiceLookUp->bank_account;
        $invoiceRecord->bank_account_num         = $invoiceLookUp->bank_account_num;
        $invoiceRecord->product_name             = $activity->name;
        $invoiceRecord->amount                   = $activity->cost * $activityJoinNum;
        $invoiceRecord->save();

        return response()->json(['level' => 'success','message' => '提交成功','data' => $invoiceRecord]);
    }
}
